package com.tensquare.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

/**
 * @author zzb
 * @version 1.0
 * @create 2020/12/23 11:18
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "jwt.config")//去掉jwt。config前缀
public class JwtUtil {
    private String key; //加密key
    private long ttl;   //到期时间


    /**
     * 创建jwt得token
     */
    public String createJwt(String id,String subject,String role){
        //设置当前时间
        Date dt = new Date();
        //定义过期时间
        Date expirDate = null;
        //判断ttl是否有值

        //开始生成token
        JwtBuilder jwtBuilder = Jwts.builder().
                setId(id)
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS256, key).claim("role", role);
        if (ttl > 0){
            expirDate = new Date(dt.getTime()+ttl);
            jwtBuilder.setExpiration(expirDate);
        }
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token
     */
    public Claims parseJwt(String token){
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }
}
